// subPages/communityService/secondHandMallDetails/secondHandMallDetails.js
import {base64Src} from "../../../utils/base64Src";
import share from "../../../utils/share";

const app = getApp();
var utils = require('../../../utils/util');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    themeColor:app.globalData.themeColor,
      indicatorDots: true,
      vertical: false,
      autoplay: true,
      circular: true,
      interval: 4000,
      duration: 500,
      previousMargin: 0,
      nextMargin: 0,
      indicatorColor:"raba(255,255,255,.3)",
      indicatorActiveColor:"#ffffff",
      imgWidth:wx.getSystemInfoSync().windowWidth,
  },
    //获取swiper 图片高度
    imgHeight:function(e){
        var winW = wx.getSystemInfoSync().windowWidth;
        var imgW = e.detail.width;
        var imgH = e.detail.height;
        var swiperH = winW*imgH/imgW+"px";
        console.log(swiperH,winW,imgH,imgW);
        this.setData({
            Height:swiperH
        })
    },
    checkImg:function(e){
        let cur = e.target.dataset.src;
        let imgArr = [];
        let goodsInfo = this.data.goodsInfo.head_img;
        for(var i=0;i<goodsInfo.length;i++){
            imgArr.push(goodsInfo[i].url);
        }
        wx.previewImage({
            current:cur,
            urls:imgArr
        })
    },
    makecall(e){
      let phoneNum = e.currentTarget.dataset.phone;
      wx.makePhoneCall({
          phoneNumber:phoneNum
      })
    },
    //分享按钮
    shareBtn:function(e){
        var currentStatus = e.currentTarget.dataset.status;
        this.shareAnim(currentStatus);
    },

    //取消按钮
    cancelBtn:function(e){
        var type = e.currentTarget.dataset.type;
        switch (type) {
            case 'share':
                var currentStatus = 'cancel';
                this.shareAnim(currentStatus);
                break;
            case 'friends':
                this.setData({
                    isFriends: false
                })
                break;
        }

    },

    //动画部分
    shareAnim: function (currentStatus) {
        // 第1步：创建动画实例
        var animation = wx.createAnimation({
            duration: 200,  //动画时长
            timingFunction: "linear", //线性
            delay: 0  //0则不延迟
        });

        // 第2步：这个动画实例赋给当前的动画实例
        this.animation = animation;

        // 第3步：执行第一组动画：Y轴偏移240px后(盒子高度是400px)，停
        animation.translateY(130).step();

        // 第4步：导出动画对象赋给数据对象储存
        this.setData({
            shareAnim: animation.export()
        })

        // 第5步：设置定时器到指定时候后，执行第二组动画
        setTimeout(function () {
            // 执行第二组动画：Y轴不偏移，停
            animation.translateY(0).step()
            // 给数据对象储存的第一组动画，更替为执行完第二组动画的动画对象
            this.setData({
                shareAnim: animation
            })

            //完成
            if (currentStatus == "cancel") {
                this.setData(
                    {
                        isShare: false,
                    }
                );
            }
        }.bind(this), 200)

        // 显示抽屉
        if (currentStatus == "open") {
            this.setData(
                {
                    isShare: true,
                }
            );
        }
    },

    //朋友圈按钮
    friendsCircleBtn:function(){
        var that = this
        //获得二维码
        wx.request({
            url: app.globalData.apiUrl +'/Api/GetUser/getWxcode',
            data: {
                page: 'subPages/communityService/secondHandMallDetails/secondHandMallDetails',
                scene: that.data.goodsInfo.id
            },
            method: 'get',
            header: {
                'content-type': 'application/json' //默认值
            },
            success: function (res) {
                console.log(res)
                base64Src(res.data, code => {
                    console.log(code) // 返回图片地址，直接赋值到image标签即可
                    that.setData({
                        isFriends: true,
                        codeimg: res.data,
                        template: new share().palette(that.data.goodsInfo.head_img,that.data.goodsInfo.price,that.data.goodsInfo.product_name,that.data.goodsInfo.sub_content,code),
                    })
                })
            },
            fail: function (res) {
                console.log("失败",res);
            }
        })

    },

    onImgOK(e) {
        this.setData({
            imagePath: e.detail.path
        })
    },

    //保存图片
    savePicBtn:function(){
      var that = this;
        wx.getSetting({
            success(res) {
                // console.log(res)
                //没有授权
                if (!res.authSetting['scope.writePhotosAlbum']) {
                    wx.authorize({
                        scope:'scope.writePhotosAlbum',
                        success() {
                            console.log('授权成功')
                        }
                    })
                }
            }
        })
        wx.saveImageToPhotosAlbum({
            filePath: this.data.imagePath,
            success:function(res) {
                utils.showToast('保存图片成功','success',1000)
                that.setData({
                    isFriends: false
                })
                var currentStatus = 'cancel';
                that.shareAnim(currentStatus);
            },
            fail: function (err) {
                // console.log(err)
                if (err.errMsg === "saveImageToPhotosAlbum:fail:auth denied" || err.errMsg === "saveImageToPhotosAlbum:fail authorize no response" || err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
                    wx.showModal({
                        title: '提示',
                        content: '请重新授权保存相册',
                        showCancel: false,
                        success:modalSuccess=>{
                            wx.openSetting({
                                success(settingdata) {
                                    // console.log("settingdata", settingdata)
                                    if (settingdata.authSetting['scope.writePhotosAlbum']) {
                                        util.showModal('提示','获取权限成功,再次点击图片即可保存')
                                    } else {
                                        util.showModal('提示','获取权限失败，将无法保存到相册哦~')
                                    }
                                },
                                fail(err) {
                                    // console.log("err",err)
                                }
                            })
                        }
                    })
                }
            },
        })
    },
    
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        utils.setNavBarTitle('商品详情');
        if(options.id){
            this.setData({
                goodsId:options.id
            });
        }
        if(options.scene){
            this.setData({
                goodsId:decodeURIComponent(options.scene)
            })
        }
        this.getContent();
    },
    getContent(){
      let _this = this;
      utils.getAjax(`${app.globalData.apiUrl}/get_old_product_content`,res=>{
          console.log(res);
          _this.setData({
              goodsInfo:res.data
          })
      },{
          id:_this.data.goodsId
      })
    },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    if(res.form == 'button'){

    }
    return {
        title: this.data.goodsInfo.product_name,
        path: `subPages/communityService/secondHandMallDetails/secondHandMallDetails?id=${this.data.goodsId}` // 分享后打开的页面
    }
  }
})
